package com.lx.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取请求参数，文件名称
        String filename = request.getParameter("filename");
        //2.使用字节输入流加载文件进内存
        //2.1 找到文件服务器路径
        ServletContext context = this.getServletContext();
        String realPath = context.getRealPath("img/" + filename);
        System.out.println(realPath);
        //2.2 用字节流关联
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(realPath);
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage() +
                    "请确认文件路径及文件名是否正确！");
        }

        //3. 设置response响应头
        //3.1 设置响应头类型： context-type
        String mimeType = context.getMimeType(filename);
        response.setHeader("content-type", mimeType);

        //3.2 设置响应头打开方式为content-disposition
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        //4. 将输入流的数据写入到输出流
        ServletOutputStream sos = response.getOutputStream();
        byte[] buff = new byte[2014 * 8];
        int len = 0;
        while ((len = fileInputStream.read(buff)) != -1) {
            sos.write(buff, 0, len);
        }
        System.out.println("downloadServlet...");


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
